package com.gitee.zhziyun.cnfsystem.ui;

import com.gitee.zhziyun.cnfsystem.config.AvatarConfig;
import com.gitee.zhziyun.cnfsystem.model.LoginData;
import com.gitee.zhziyun.cnfsystem.utils.IpAddressUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Objects;

public class LoginUI extends JFrame {
    // 窗口组件
    private final JPanel topPanel = new JPanel();
    private final JPanel centerPanel = new JPanel();
    private final JPanel rootPanel = new JPanel();

    // 表单组件
    private final JTextField userName = new JTextField(19);
    private final JLabel avatar = new JLabel();
    private final JComboBox<String> comboBoxOfAvatarId = new JComboBox<>(AvatarConfig.getNameList());
    private final JComboBox<String> comboBoxOfSubnet = new JComboBox<>(IpAddressUtil.getAllLocalSubnets());
    private final JSpinner heartBeatPort = new JSpinner(new SpinnerNumberModel(2425, 1024, 65535, 1));
    private final JButton loginBtn = new JButton("确认登录");

    // 全局变量
    private int avatarId = 0;

    // 同步锁
    private final Object lock;

    public LoginUI(Object lock) {
        // 窗口设置
        setTitle("登录");  // 添加窗口标题
        setSize(300, 450);// 设置窗口大小
        setResizable(false);// 设置窗口大小不可变
        setLocationRelativeTo(null);// 窗口居中
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 设置关闭窗口时退出程序

        // 初始化组件（保持原有解耦结构）
        initTopPanel();// 初始化顶部面板
        initCenterPanel();// 初始化中间面板
        initRootPanel();// 初始化根面板

        // 添加监听器
        addListener();

        add(rootPanel);
        this.lock = lock;
        setVisible(true);
    }

    private void initTopPanel() {
        topPanel.setLayout(new BorderLayout());
        topPanel.setBorder(BorderFactory.createEmptyBorder(20, 0, 20, 0)); // 添加内边距

        // 头像设置
        setAvatar(avatarId);
        JPanel avatarContainer = new JPanel(new FlowLayout(FlowLayout.CENTER));
        avatarContainer.add(avatar);

        topPanel.add(avatarContainer, BorderLayout.CENTER);
    }

    private void initCenterPanel() {
        // 主面板使用BoxLayout纵向排列
        centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS));
        centerPanel.setBorder(BorderFactory.createEmptyBorder(20, 40, 20, 40)); // 添加内边距

        // 用户名行
        userName.setPreferredSize(new Dimension(0, 25)); // 高度固定，宽度自动填充
        centerPanel.add(createFormRow(createLabel("用户名："), userName));
        centerPanel.add(Box.createVerticalStrut(15));

        // 头像选择行
        comboBoxOfAvatarId.setPreferredSize(new Dimension(0, 30));
        comboBoxOfAvatarId.setSelectedIndex(avatarId);
        centerPanel.add(createFormRow(createLabel("头像："), comboBoxOfAvatarId));
        centerPanel.add(Box.createVerticalStrut(15));

        // 子网选择行
        comboBoxOfSubnet.setPreferredSize(new Dimension(0, 30));
        centerPanel.add(createFormRow(createLabel("子网："), comboBoxOfSubnet));
        centerPanel.add(Box.createVerticalStrut(15));

        // 端口行
        heartBeatPort.setPreferredSize(new Dimension(0, 30));
        centerPanel.add(createFormRow(createLabel("端口："), heartBeatPort));

        // 登录按钮
        centerPanel.add(Box.createVerticalStrut(25));
        loginBtn.setAlignmentX(Component.CENTER_ALIGNMENT); // 按钮居中
        loginBtn.setPreferredSize(new Dimension(250, 35));
        centerPanel.add(loginBtn);
    }

    private void initRootPanel() {
        rootPanel.setLayout(new BorderLayout());
        rootPanel.add(topPanel, BorderLayout.NORTH);
        rootPanel.add(centerPanel, BorderLayout.CENTER);
    }

    private void addListener() {
        JFrame frame = this;
        // 头像区监听器
        comboBoxOfAvatarId.addActionListener(e -> {
            //渲染选择的头像
            avatarId = AvatarConfig.getIdByName((String) comboBoxOfAvatarId.getSelectedItem());
            setAvatar(avatarId);
        });

        // 登陆案件监听器
        loginBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                String name = userName.getText().trim();

                if (name.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "用户名不得为空", "错误", JOptionPane.ERROR_MESSAGE);
                } else if ((int) heartBeatPort.getValue() < 1024 || (int) heartBeatPort.getValue() > 65535) {
                    JOptionPane.showMessageDialog(null, "端口号不得小于1024且不得大于65535", "错误", JOptionPane.ERROR_MESSAGE);
                } else {
                    //控制台输出
                    System.out.println("获取的信息：");
                    System.out.print("用户名：");
                    System.out.println(name);
                    System.out.print("选中的头像：");
                    System.out.println(comboBoxOfAvatarId.getSelectedItem());
                    System.out.print("头像的ID：");
                    System.out.println(avatarId);
                    System.out.print("选择的子网：");
                    System.out.println((String) comboBoxOfSubnet.getSelectedItem());
                    System.out.print("端口编号：");
                    System.out.println((int) heartBeatPort.getValue());

                    synchronized (lock) { lock.notify(); }
                    frame.dispose();
                }
            }
        });
    }

    // 创建等宽标签的方法
    private JLabel createLabel(String text) {
        JLabel label = new JLabel(text);
        label.setPreferredSize(new Dimension(50, 25)); // 统一标签宽度
        label.setHorizontalAlignment(SwingConstants.RIGHT); // 标签文本右对齐
        return label;
    }

    // 创建表单行的方法
    private JPanel createFormRow(JLabel label, JComponent field) {
        JPanel rowPanel = new JPanel(new BorderLayout(10, 0)); // 水平间距10
        rowPanel.setOpaque(false); // 透明背景
        rowPanel.add(label, BorderLayout.WEST);
        rowPanel.add(field, BorderLayout.CENTER);
        return rowPanel;
    }

    // 设置头像
    private void setAvatar(int avatarId) {
        ImageIcon originalIcon = new ImageIcon(Objects.requireNonNull(
                LoginUI.class.getResource(AvatarConfig.getPathById(avatarId))));
        Image scaledImg = originalIcon.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH);
        avatar.setIcon(new ImageIcon(scaledImg));
    }

    public LoginData getLoginData() {

        return new LoginData(userName.getText(), avatarId, (String) comboBoxOfSubnet.getSelectedItem(), (int) heartBeatPort.getValue());// 提交登录数据至启动流程

    }
}